package com.polaris.live.viewmodel.backpack

import androidx.lifecycle.MutableLiveData
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.ApiResponse
import com.polaris.live.common.network.getSuccessResult
import com.polaris.live.common.network.new
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.UserBackpackDecorationResp
import com.polaris.live.resp.back_resp.UserBackpackMergeResp
import com.polaris.live.resp.back_resp.UserBackpackNewAllResp
import com.polaris.live.resp.back_resp.UserPartyBackgroundListResp
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope

/**
 * BackPackViewModel 背包Model
 *
 * @author Created by 天晴 on 2024/1/17 9:15
 * @since 1.0.0
 **/
class BackPackMainModel : BaseViewModel() {

    //背包数据请求
    val mBackpackLiveData = MutableLiveData<ResultState<UserBackpackMergeResp>>()

    fun getBackpack() {
        requestLoading({
            coroutineScope {
                val backpackDef = async {
                    userService.getUserBackpack()
                }
                val consumableDef = async {
                    try {
                        userService.getConsumableList()
                    } catch (t: Throwable) {
                        ApiResponse.error(500, t.message ?: "network error")
                    }
                }
                val numberDef = async {
                    try {
                        userService.getNumberList()
                    } catch (t: Throwable) {
                        ApiResponse.error(500, t.message ?: "network error")
                    }
                }

                val backpack = backpackDef.await()

                backpack.new(
                    UserBackpackMergeResp(
                        backpack.getSuccessResult(),
                        consumableDef.await().getSuccessResult(),
                        numberDef.await().getSuccessResult()
                    )
                )
            }
        }, mBackpackLiveData, waitTime = 0)
    }

    val mBackpackNewAllLiveData = MutableLiveData<ResultState<UserBackpackNewAllResp>>()

    /**
     * 获取道具红点
     */
    fun getBackpackNewAll() {
        request({ userService.getBackpackNewAll() }, mBackpackNewAllLiveData)
    }

    //获取派对游戏列表和背包列表
    val mDiyAndBackLiveData = MutableLiveData<Pair<UserPartyBackgroundListResp?, List<UserBackpackDecorationResp>>>()
    fun getDiyBackpack(data: List<UserBackpackDecorationResp>) {
        request({
            userService.getPartyDiyBackground()
        }, {
            mDiyAndBackLiveData.value = Pair(it, data)
        }, {
            mDiyAndBackLiveData.value = Pair(null, emptyList())
        })
    }
}